package com.esteel.settlement.config.pa;

import java.io.IOException;
import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;

import com.esteel.settlement.pa.packet.PaPacket;
import com.esteel.settlement.service.PacketLogger;

/**
 * 平安结算报文 自动转换程序
 * 
 * @author zhangxiuzhi
 *
 */
public class PaHttpMessageConverter extends AbstractHttpMessageConverter<PaPacket> {

	private Logger logger =  LoggerFactory.getLogger(this.getClass());
	
	private Charset packetEncoding = Charset.forName("GBK");

	@Override
	protected boolean supports(Class<?> clazz) {
		return true;
	}

	public boolean canRead(Class<?> clazz, MediaType mediaType) {
		return true;
	}

	public boolean canWrite(Class<?> clazz, MediaType mediaType) {
		return true;
	}

	@Override
	protected PaPacket readInternal(Class<? extends PaPacket> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		String packetStr = StreamUtils.copyToString(inputMessage.getBody(), packetEncoding);

		logger.info(packetStr);
		PacketLogger.log(packetStr);
		
		Assert.isTrue(packetStr.getBytes("GBK").length > 222,"服务器报文不正确");
		try {
			PaPacket packet = clazz.newInstance();

			packet.analyze(packetStr);

			return packet;
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();

		}
		return null;
	}

	@Override
	protected void writeInternal(PaPacket packet, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
		String marshalStr = packet.marshal();
		logger.info(marshalStr);
		PacketLogger.log(marshalStr);
		StreamUtils.copy(marshalStr, packetEncoding, outputMessage.getBody());

	}

}
